package common.rssReader;

import java.net.ConnectException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;


import org.w3c.dom.Document;
import org.w3c.dom.Node;

import common.DateUtils;

import play.libs.WS;
import play.libs.WS.HttpResponse;
import play.libs.WS.WSRequest;
import play.libs.XPath;

public class RssReader {
	private static RssReader instance;
    private String rssPubDateFormat = "EEE, dd MMM yyyy HH:mm:ss z";
	private Rss rss;
	private List<String> rssUrls;
	public static Date lastReadedTime = null;
    public static RssReader getInstance() {
		if (instance == null) {
			instance = new RssReader();
		    
		}
		
		return instance;
	}

	private RssReader(){
		rss = new Rss();
		
	}
   
	public Rss readRss(int count) {
		return null;
	
	}

	
	public Rss readRss() {
		if (rssUrls != null && rssUrls.size() > 0) {
		
	   	   for(String rssUrl:rssUrls){
	   		
			 WSRequest request = WS.url(rssUrl);
		 	 HttpResponse response = request.get();
			 Document document = response.getXml();
             ParseRssDocument(document);
		   }
	 }
		return rss;
	}
    /**
     * 
     * @param rssUrl
     * @param lastReadedRssTime
     * @return rss that are public after lastReadedRssTime
     */
	public Rss readRss(Date lastReadedRssTime) throws TimeoutException, ExecutionException{
	  System.out.println("lastReadedTime: "+lastReadedRssTime.toGMTString()+" " +lastReadedRssTime.toLocaleString());	
	   if(rss != null && rss.getRssItems() != null &&  rss.getRssItems().size() > 0){ //Onceki RssLeri bosaltmak
		   rss.getRssItems().clear();
	   }
		String  tempUrl="";
		try{
	
		if(rssUrls != null && rssUrls.size() > 0){
	    for(String rssUrl : rssUrls){
		   WSRequest request = WS.url(rssUrl);
		   HttpResponse response = request.get();  
		   Document document = response.getXml();
		   ParseRssDocument(document,lastReadedRssTime);
	       }		
	      }
		 }catch (RuntimeException e) {
		       System.out.println("<HATA>");
		       System.out.println("In RssReader  rssUrl: "+ tempUrl);
		       System.out.println("<HATA>");
		       rss.getRssItems().clear();
			}

	   
      return rss;
	}
    
    
    public void ParseRssDocument(Document rssDocument) {
		String xpathItemSelector = "rss//" + RssTags.CHANNEL + "//"
				+ RssTags.ITEM;
		List<Node> nodeList = XPath.selectNodes(xpathItemSelector, rssDocument);
		for (Node item : nodeList) {
			String title = XPath.selectText(RssTags.TITLE, item);
			String link = XPath.selectText(RssTags.LINK, item);
			String desc = XPath.selectText(RssTags.DESCRIPTION, item);
			
			//rss.addRssItem(link, title, desc);
		}
	}
  
    public void ParseRssDocument(Document rssDocument, Date lastReadedRssTime){
        
         String xpathItemSelector = "rss//" + RssTags.CHANNEL + "//" + RssTags.ITEM;
         String xpathLastBuildDateSelector = "rss//" + RssTags.CHANNEL;
         Node lastBuildDateNode = XPath.selectNode(xpathLastBuildDateSelector, rssDocument);
         String lastBuildDateString = XPath.selectText("lastBuildDate", lastBuildDateNode);
         if(lastBuildDateString == null){
        	 lastBuildDateString = XPath.selectText("pubDate", lastBuildDateNode);
         }
       
         
         List<Node> nodeList = XPath.selectNodes(xpathItemSelector, rssDocument);
         if(nodeList.size() > 0){
        	
        	 for(Node item : nodeList){
        		 String pubDate = XPath.selectText(RssTags.PUB_DATE, item);
        		 //pubDate = pubDate.substring(0, pubDate.length()-4);
        		 
        		 Date rssItemDate = DateUtils.convertStringToDate(pubDate.trim(), this.rssPubDateFormat);
        	   	
        	
        		
        		 if(DateUtils.isAfterDate(rssItemDate, lastReadedRssTime)){
        			 System.out.println(" new rss pub date :"+pubDate +"--date: "+ rssItemDate.toString());
        			 String title = XPath.selectText(RssTags.TITLE, item);
        				String link = XPath.selectText(RssTags.LINK, item);
        				String desc = XPath.selectText(RssTags.DESCRIPTION, item);
        			
        				rss.addRssItem(link, title, desc,rssItemDate);     			 
        		 }
        	 }
         }
       
    }
    
    
    public void addRssUrl(String url){
    	if(rssUrls == null || rssUrls.size() < 1){
    		rssUrls = new ArrayList<String>();
    	}
    	rssUrls.add(url);
    }
    public void removeAllRssUrls(){
    	 if(rssUrls != null){
    		 rssUrls.clear();
    	 }
    }
     /*
    private void addRssItem(String link , String title , String desc){
    	
    }
    */
}
